package com.ybt.heartratem.common.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 画板视图
 * @author Administrator
 *
 */
public class WrittingView  extends View{
	private Canvas mCanvas;
	private Bitmap mBitmap;
	private Paint paint = null;
	public WrittingView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	/**
	 * 初始化
	 */
	private void init(){
		paint = new Paint();
		paint.setAntiAlias(true);
		paint.setFlags(Paint.ANTI_ALIAS_FLAG);
		paint.setColor(Color.BLACK);
		paint.setStrokeWidth(5);
		mCanvas = new Canvas();
		mCanvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
	}

	/**
	 * 清屏
	 */
	public void clearAll(){
		mCanvas.drawColor(Color.WHITE);
		invalidate();
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		try {
			int[] pixels = new int[w * h];

			for (int y = 0; y < h; y++) {
				for (int x = 0; x < w; x++) {
					pixels[y * w + x] = Color.WHITE;
				}
			}
			mBitmap = Bitmap.createBitmap(w, h,Bitmap.Config.RGB_565);
			mBitmap.setPixels(pixels, 0, w, 0, 0, w, h);
			mCanvas.setBitmap(mBitmap);
			super.onSizeChanged(w, h, oldw, oldh);
		}catch (Exception e){
			e.printStackTrace();
		}

	}

	private float startX = 0;
	private float startY = 0;
	private float stopX = 0;
	private float stopY = 0;
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int action=event.getAction();
		switch(action){
			case MotionEvent.ACTION_DOWN://点击
				//在这里获取起始点坐标
				startX = event.getX();
				startY = event.getY();
				break;
			case MotionEvent.ACTION_MOVE://移动
				//在这里获取移动点坐标
				stopX = event.getX();
				stopY = event.getY();
				mCanvas.drawLine(startX, startY, stopX, stopY, paint);//绘图
				//把末点赋值给始点
				startX = stopX;
				startY = stopY;
				invalidate();
				break;
			case MotionEvent.ACTION_UP://收笔
				stopX = event.getX();
				stopY = event.getY();
				invalidate();
				break;
			default:
				break;
		}
		return true;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.drawBitmap(mBitmap,0 , 0, null);
	}
	/**
	 * 将画布的内容保存到文件
	 * @param filename
	 * @throws FileNotFoundException
	 */
	public void saveToFile(String filename) throws FileNotFoundException {
		File f = new File(filename);
		if(f.exists())
			throw new RuntimeException("文件：" + filename + " 已存在！");
		FileOutputStream fos = new FileOutputStream(new File(filename));
		mBitmap.compress(CompressFormat.PNG, 65, fos);
		try {
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
